/*
 * @desc:
 * @author: mao
 * @version: 1.0
 * @Date: 2023-08-14 11:49:03
 */
import { message } from "ant-design-vue";
import axios from "axios";
import dayjs from "dayjs";
import { useRouter, useRoute } from "vue-router";
import signature from "@/utils/signature";


const VUE_APP_SIGN_KEY='FdRLuS55fKUy8UczZrnyKA';
const VUE_APP_SIGN_SECRET='qmUh91JBQNHXRWFQH5faSJpxjrwa_bkAjUu7U6u7gJs';

const router = useRouter();
export const CancelToken = axios.CancelToken;
const request = axios.create({
    baseURL: "/",
    timeout: 60000,
});

async function updateToken(expires_in: number, token: string) {
    let end = dayjs(Number(expires_in));
    let start = dayjs();
    let offset = end.diff(start, "h");

    if (offset < 2) {
        let prefix = "";

        prefix = process.env.VUE_APP_PREFIX || "";

        let res = await request.post<
            Response<{ access_token: string; expires_in: number }>
        >(`${prefix}/usersys-app/access-token/refresh`, {
            old_access_token: token,
        });
        let data = res.data.result.data;
        if (data) {
            window.microApp.dispatch({
                type: "UPDATETOKEN",
                token: data.access_token,
                expires_in: data.expires_in,
            });
            return data.access_token;
        }
        return token;
    }
    return token;
}

const appKey = VUE_APP_SIGN_KEY;
const appSecret = VUE_APP_SIGN_SECRET;

request.interceptors.request.use(async (req) => {
    let globalData = window.microApp.getGlobalData();
    if (globalData) {
        let token = globalData.token;
        let expires_in = globalData.expires_in;
        req["headers"]["Authorization"] = `Bearer ` + token;

        if (!req.url?.includes(`/usersys-app/access-token/refresh`)) {
            let newToken = await updateToken(expires_in, token);
            req["headers"]["Authorization"] = `Bearer ` + newToken;
        }
    }

    req["headers"]["BZ-HEADER-DEVICE"] = "pc";

    let signObj = signature(appKey, appSecret, req);
    Object.assign(req["headers"], signObj);

    let url = req.url;
    let prefix = "";
    prefix = process.env.VUE_APP_PREFIX || "";

    if (url?.includes("https://") || url?.includes("http://")) {
    } else {
        req.url = prefix + url;
    }

    return req;
});

request.interceptors.response.use(
    (res) => {
        if (res.status == 200) {
            if (res.data.status_code == 1) {
                // 请求成功
            } else {
                if (res.data.status_code != 10 && res.data.msg) {
                    if(res.data.status_code != 102){
                        message.error(res.data.msg || '接口异常');
                    }
                    // if (res.data.msg == '媒资不存在') {
                    //     setTimeout(() => {
                    //         window.microApp.dispatch({
                    //             type: "ROUTER",
                    //             name: "mrc-admin",
                    //             path: "/admin/index",
                    //         });
                    //     }, 1500);
                    // }

                    // if (res.data.msg == '文件不存在！') {
                    //     setTimeout(() => {
                    //         window.microApp.dispatch({
                    //             type: "ROUTER",
                    //             name: "mrc-admin",
                    //             path: "/netdisk/netdiskIndex",
                    //         });
                    //     }, 1500);
                    // }
                }
                return Promise.reject(res.data.msg);
            }
        }
        return res;
    },
    (err) => {
        if (err.code !== "ERR_CANCELED") {
            if (err.response.status != 404 && err.response.status == 401) {
                message.error(err.response?.data?.msg || err.message || '登陆失效');
            }
            if (err.response.status == 401) {
                window.microApp.dispatch({
                    type: "LOGOUT",
                    code: "401",
                });
            }
        }
        return Promise.reject(err);
    },
);

export default request;

export interface Pagination {
    current_page: number;
    total_count: number;
    total_pages: number;
    page_items: number;
    last_id: string;
}
export interface Response<T = any> {
    status_code: number;
    msg: string;
    result: {
        data: T;
        page: {} | Pagination;
    };
}
